$.fn.pagination.defaults.displayMsg = '';
$(function(){
    obj.init();
});

window.obj = new function(){
    'use strict';
    return {
        schDataGrid: null,
        dataGrid: null,
        params: {
            schoolId: null,
            year: null,
            vague: null,
            className: null,
            startTime: null,
            history: null,
            charge: null,
            payStatus: null,
        },
        init: function () {
            this.schDataGrid  = new xhDataGrid($('#schoolList'), 'cost/getSchools');
            this.dataGrid = new xhDataGrid($('#studList'), 'Cost/getCharge');

            this.schDataGrid.parseToolbar();//.activeBtn(null, $('#bt_sch_code'));
            $('#list_school_status').combobox('setValues', ['1', '2']);
            this.funObj().schoolSearch();
            this.dataGrid.parseToolbar();

            this.funObj().bindGridEvent();
            // this.funObj().dealJump();

            this.listener();
        },
        listener: function () {
            var $this = this;
            //学校搜索
            $('#bt_list_school_search').click(function(){
                $this.funObj().schoolSearch();
            });
            //学生搜索
            $('#bt_list_stud_search').click(function(){
                $this.funObj().studSearch();
            });
            //导入缴费信息文件
            $('#bt_list_importDetail').click(function(){
                $this.funObj().importDetail();
            });
            //调整服务时间
            $('#bt_list_time_adjustment').click(function(){
                $this.funObj().timeAdjust();
            });
            //流水导入
            $('#bt_list_importFlow').click(function () {
                $this.funObj().importFlow(1);
            });
            //姓名导入
            $('#bt_list_importNameFlow').click(function () {
                $this.funObj().importFlow(2);
            });
            //导出
            $('#bt_list_stud_export').click(function () {
                $('#bt_list_stud_search').click();
                location.href = baseUrl + 'Cost/exportCharge?' + xhTool.parseParam($this.params);
            });
            //更改编号
            $('#bt_sch_code').click(function () {
                $this.funObj().changeSchoolCode();
            });
            //审核缴费凭证
            $("#bt_list_checkPayVoucher").click(function () {
                $this.funObj().showPayVoucher();
            });
        },
        funObj: function(){
            var $this = this;
            return {
                bindGridEvent: function() {
                    $this.schDataGrid.onSelect = function (rowIndex, rowData) {
                        $this.params.schoolId = rowData.iSchoolId;
                        $this.funObj().studSearch();
                        $this.dataGrid.setTitle(null, '-' + rowData.sSchoolName);
                    };
                    $this.schDataGrid.onLoadSuccess = function (data) {
                        if (data['rows'].length <= 0) {
                            return false;
                        }
                        $this.schDataGrid.command('selectRow', 0);
                        var p = $('#studList').datagrid('getPager');
                        $(p).pagination({
                            displayMsg: '显示{from}到{to},共{total}记录',
                        });
                    };

                    $this.dataGrid.onLoadSuccess = function () {
                        $this.dataGrid.clear();

                        $('#studList').datagrid('getPanel').find('tr.datagrid-row').bind('mouseover mouseout',function(e){
                            var div = $(this).find("td[field='iSignInStatus']").children('div');
                            var span = div.children('span');
                            var img = div.children('div').html();

                            if (span.html() == '是') {
                                div.tooltip({
                                    position: 'right',
                                    content: '<img src="'+img+'" style="width:150px;">',
                                    onShow: function(){
                                        $(this).tooltip('tip').css({
                                            backgroundColor: '#fff',
                                            borderColor: '#fff'
                                        });
                                    }
                                });
                            }
                        });

                    };
                    $this.dataGrid.onDblClickRow = function (rowIndex, rowData) {
                        $this.funObj().openChargeView(rowData.year, rowData.iUserId, rowData.sUserName);
                    };
                },
                schoolSearch: function () {
                    $this.schDataGrid.reload({
                        vague: xhExtra.getValue($('#list_school_vague')),
                        status: xhExtra.getValue($('#list_school_status'))
                    });
                },
                studSearch: function () {
                    $this.params.year       = xhExtra.getValue($('#list_stud_year'));
                    $this.params.vague      = xhExtra.getValue($('#list_stud_vague'));
                    $this.params.className  = xhExtra.getValue($('#list_stud_class'));
                    $this.params.startTime  = xhExtra.getValue($('#list_startTime'));
                    $this.params.endTime    = xhExtra.getValue($('#list_endTime'));
                    $this.params.history    = xhExtra.getValue($('#list_stud_history'));
                    $this.params.charge     = xhExtra.getValue($('#list_stud_charge'));
                    $this.params.payStatus  = xhExtra.getValue($('#list_payVoucher_status'));
                    $this.dataGrid.reload($this.params);
                },
                importDetail: function () {
                    window.top.swal.setDefaults({
                        title: $this.schDataGrid.getSelectValue('sSchoolName'),
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        progressSteps: ['1', '2', '3']
                    });
                    var year,
                        serviceStart,
                        serviceEnd,
                        autoClass,
                        steps = [
                            {
                                html: '<input id="year" type="number" class="form-control" placeholder="缴费年度" style="margin-bottom: 10px;width: 50%;margin-left: 25%;"/>' +
                                    '输入服务时间：' +
                                    '<input id="serviceStart" type="date" class="form-control" placeholder="开始服务时间" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />' +
                                    '<input id="serviceEnd"  type="date" class="form-control" placeholder="结束服务时间" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />',
                                confirmButtonText: '下一步',
                                preConfirm: function() {
                                    return new Promise(function (resolve, reject) {
                                        year = $('#year', window.top.document).val();
                                        serviceStart = $('#serviceStart', window.top.document).val();
                                        serviceEnd = $('#serviceEnd', window.top.document).val();
                                        if (year < 2000 || year > 2100) {
                                            reject('缴费年份不正确！');
                                        // } else if (!serviceStart || !serviceEnd) {
                                        //     reject('服务时间不能为空！');
                                        } else {
                                            resolve();
                                        }
                                    })
                                }
                            },
                            {
                                text: '自动创建班级',
                                input: 'select',
                                inputOptions: {
                                    1: '行政班',
                                    // 2: '培优班'
                                },
                                confirmButtonText: '确认',
                                showCancelButton: false,
                                preConfirm: function(classType) {
                                    return new Promise(function (resolve, reject) {
                                        autoClass = classType;
                                        resolve();
                                    })
                                }
                            },
                            {
                                text: '导入excel文件',
                                input: 'file',
                                inputAttributes: {accept: '.xls,.xlsx'},
                                confirmButtonText: '导入',
                                preConfirm: function(file) {
                                    return new Promise(function (resolve, reject) {
                                        if (!file) {
                                            reject('文件不能为空！');
                                        } else {
                                            window.top.swal.resetDefaults();
                                            var fileData = new FormData();
                                            fileData.append('schoolId', $this.params.schoolId);
                                            fileData.append('year', year);
                                            fileData.append('file', file);
                                            fileData.append('autoClass', autoClass);
                                            fileData.append('serviceStart', serviceStart);
                                            fileData.append('serviceEnd', serviceEnd);
                                            $.ajax({
                                                url: baseUrl + 'Cost/importChargeDetail',
                                                type: 'POST',
                                                processData: false,
                                                contentType: false,
                                                data: fileData,
                                                complete: function (XMLHttpRequest) {
                                                    $this.funObj().dealImportResult(XMLHttpRequest.responseJSON);
                                                }
                                            });
                                        }
                                    })
                                }
                            }
                        ];
                    window.top.swal.queue(steps).then(function(result) {}, function(dismiss) {window.top.swal.resetDefaults();});
                },
                importFlow: function (type) {
                    window.top.swal.setDefaults({
                        title: type === 2
                            ? $this.schDataGrid.getSelectValue('sSchoolName')
                            : '流水导入',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        progressSteps: ['1', '2']
                    });
                    var year,
                        steps = [
                            {
                                text: '输入缴费年度' + (type === 2 ? '(姓名导入)' : '(流水导入)'),
                                input: 'number',
                                confirmButtonText: '下一步',
                                preConfirm: function(chargeYear) {
                                    return new Promise(function (resolve, reject) {
                                        if (year < 2000 || year > 2100) {
                                            reject('缴费年份不正确！');
                                        } else {
                                            year = chargeYear;
                                            resolve();
                                        }
                                    })
                                }
                            },
                            {
                                text: '导入excel文件',
                                input: 'file',
                                inputAttributes: {accept: '.xls,.xlsx'},
                                confirmButtonText: '导入',
                                preConfirm: function(file) {
                                    return new Promise(function (resolve, reject) {
                                        if (!file) {
                                            reject('文件不能为空！');
                                        } else {
                                            window.top.swal.resetDefaults();
                                            var fileData = new FormData();
                                            fileData.append('schoolId', $this.params.schoolId);
                                            fileData.append('year', year);
                                            fileData.append('file', file);
                                            fileData.append('type', type);
                                            $.ajax({
                                                url: baseUrl + 'Cost/importChargeFlow',
                                                type: 'POST',
                                                processData: false,
                                                contentType: false,
                                                data: fileData,
                                                complete: function(XMLHttpRequest){
                                                    $this.funObj().dealImportResult(XMLHttpRequest.responseJSON);
                                                }
                                            });
                                        }
                                    })
                                }
                            }
                        ];
                    window.top.swal.queue(steps).then(function(result) {}, function(dismiss) {window.top.swal.resetDefaults();});
                },
                dealImportResult: function (result) {
                    if(xhExtra.checkError(result)) return false;
                    if (result.errorData.length > 0){
                        var content = '';
                        $.each(result.errorData, function(index, row){
                            // content += `<tr><td>${row.name}</td><td>${row.code}</td><td>${row.reason}</td></tr>`;
                            content += '<tr><td>' + row.name + '</td><td>' + row.code + '</td><td>' + row.reason + '</td></tr>';
                        });
                        window.top.swal({
                            title: result.msg,
                            type: 'warning',
                            html: '<table class="table table-striped"><tr>' +
                            '<th style="text-align: center">学生</th>' +
                            '<th style="text-align: center">缴费编号</th>' +
                            '<th style="text-align: center">原因</th>' +
                            '</tr>' + content + '</table>'
                        });
                    }
                    else{
                        window.top.xhTop.showSuccess(result.msg);
                    }
                    $this.dataGrid.reload();
                },
                openChargeView: function (year, userId, userName) {
                    window.top.xhTop.showModal({
                        title: userName + '-' + year,
                        content: xhTool.getFrameString('cost/detailAndFlow', {userId: userId, year: year}, 600),
                        size: 'lg',
                        button: true
                    });
                },
                changeSchoolCode: function () {
                    var schoolId = $this.schDataGrid.getSelectValue('iSchoolId');
                    if (!schoolId) {
                        window.top.xhTop.showError('请选择学校！');
                        return false;
                    }
                    window.top.swal({
                        title: '更改编号',
                        text: $this.schDataGrid.getSelectValue('sSchoolName'),
                        input: 'text',
                        inputValue: $this.schDataGrid.getSelectValue('sCode'),
                        showConfirmButton: true,
                        showCancelButton: true,
                        confirmButtonText: '更改',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        preConfirm: function (code) {
                            return new Promise(function (resolve, reject) {
                                if (!code) {
                                    reject('编号不能为空！');
                                } else {
                                    xhExtra.ajaxRequest(
                                        'cost/changeSchoolCode',
                                        {schoolId: schoolId, code: code},
                                        {check: true, success: true, table: $this.schDataGrid}
                                    );
                                }
                            })
                        }
                    });
                },
                showPayVoucher: function () {
                    var year = xhExtra.getValue($('#list_stud_year'));
                    var userIds = $this.dataGrid.getSelectValues('iUserId');
                    window.top.xhTop.showModal({
                        title: '审核凭证',
                        content: xhTool.getFrameString('school/showPayVoucher', {userIds:userIds, year:year}, 500),
                        size: 'lg',
                        width: 820,
                        backClose: false
                    });
                },
                timeAdjust: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中用户');
                        return false;
                    }
                    window.top.swal({
                        title: '调整服务时间',
                        html: '输入服务时间：' +
                            '<input id="serviceStart" type="date" class="form-control" placeholder="开始服务时间" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />' +
                            '<input id="serviceEnd"  type="date" class="form-control" placeholder="结束服务时间" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />',
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var serviceStart = $('#serviceStart', window.top.document).val();
                                var serviceEnd = $('#serviceEnd', window.top.document).val();
                                if(!serviceStart || !serviceEnd){
                                    reject('请输入服务时间！');
                                } else {
                                    xhExtra.ajaxRequest(
                                        'Cost/serviceTimeAdjust',
                                        {ids: ids, serviceStart: serviceStart, serviceEnd: serviceEnd},
                                        {success: true, table: $this.dataGrid},
                                        function () {
                                            $this.classGrid.reload();
                                        }
                                    );
                                    resolve();
                                }
                            })
                        }
                    }).then(function(isConfirm) {}, function(dismiss) {});
                }
            }
        }
    }
}
